// 添加人员

<template>
    <div @touchmove.prevent>
        <van-popup
            v-model="visible"
            position="bottom"
            class="popup-bg"
            get-container="body"
            :style="{ height: '100%', background: '#F4F6F9' }"
            :lock-scroll="false"
        >
            <f7-page>
                <f7-navbar>
                    <f7-nav-left>
                        <f7-link
                            @click="fnColse"
                            icon-material="chevron_left"
                            force
                        ></f7-link>
                    </f7-nav-left>
                    <f7-nav-title>选择标准节</f7-nav-title>
                    <f7-nav-right> </f7-nav-right>
                </f7-navbar>
                <div class="search-box">
                    <van-search
                        v-model="otherSearch"
                        @search="searchQuery"
                        @clear="reset"
                        shape="round"
                        show-action
                        background="#1990ff"
                        placeholder="永久性标识/自编号"
                    >
                        <template #action>
                            <div @click="searchQuery" class="search-bar-btn">搜索</div>
                        </template>
                    </van-search>
                </div>
                <div class="radio-list">
                    <van-list
                        class="search-list"
                        v-model="loading"
                        :finished="finished"
                        finished-text="没有更多了"
                        @load="dataQuery"
                        v-if="query.data.length > 0"
                        @scroll.native="onScroll"
                        :offset="100"
                    >
                        
                        <van-checkbox-group v-model="result">
                            <li
                                v-for="(item, index) in query.data"
                                :key="index"
                                @click="item.useStatus!='闲置'?'':toggle(item, index)"
                            >
                                <van-checkbox
                                    :name="item.sectionId"
                                    shape="square"
                                    :disabled="item.useStatus!='闲置'"
                                    ref="checkboxes"
                                ></van-checkbox>
                                <div class="search-list-item">
                                    <h3>
                                        {{item.identification}} 
                                        <span class="tag tag-blue" v-if="item.useStatus=='闲置'">{{item.useStatus}}</span>
                                        <span class="tag tag-red" v-else>{{item.useStatus}}</span>
                                    </h3>
                                    <p>
                                        <span class="qzjx_label">自编号：</span>
                                        <span class="qzjx_value">{{item.sectionCode}}</span>
                                    </p>
                                    <p>
                                        <span class="qzjx_label">配塔基类型：</span>
                                        <span class="qzjx_value">{{item.craneType}}</span>
                                    </p>
                                    <p>
                                        <span class="qzjx_label">产权单位：</span>
                                        <span class="qzjx_value">{{item.enterpriseName}}</span>
                                    </p>
                                    <p>
                                        <span class="qzjx_label">制造厂商：</span>
                                        <span class="qzjx_value">{{item.makeCompany}}</span>
                                    </p>
                                    <p style="color:red">
                                        <span class="qzjx_label">一年内违章作业：</span>
                                        <span class="qzjx_value">{{item.warnText}}</span>
                                    </p>
                                </div>
                            </li>
                        </van-checkbox-group>
                    </van-list>
                    <v-empty v-else description="暂无数据" />
                </div>
                
                <f7-toolbar position="bottom" no-shadow class="fff">
                    <span>已选{{ result.length }}项</span>
                    <f7-button fill class="submit-btn" @click="fnSave()"
                        >提交</f7-button
                    >
                </f7-toolbar>
            </f7-page>
        </van-popup>
    </div>
</template>

<script>
import Config from '@/libs/config.js'
export default {
    name: 'v-popup-person',
    props: {
        value: {
            type: Boolean,
            default: false,
            required: true,
        },
        // 操作后自动关闭组件
        autoClose: {
            type: Boolean,
            default: true,
        },
        url: {
            type: String,
        },
        chooseList:{
            type:Array,
            required: true,
        },
        craneType:String
    },
    computed: {
        visible: {
            get() {
                if(this.value==true&&this.chooseList.length>0){
                    this.lastChooseList=this.chooseList.map(item=>item.sectionId)
                    this.result=JSON.parse(JSON.stringify(this.lastChooseList))
                }
                return this.value
            },
            set(val) {
                this.$emit('input', val)
            },
        },
    },
    data() {
        return {
            otherSearch: '',
            result: [],
            query: {
                data: [],
            },
            start: 0,
            length: 10,
            recordsTotal: null,
            loadFlag: true,
            download: Config.api.download,
            lastChooseList:[],
            nowChooselist:[],
            loading: false,
            finished: false,
            list:[],
        }
    },
    created() {
        this.searchQuery()
    },
    methods: {
        onScroll(event) {
            console.log("🚀 ~ file: v-popup-person.vue:175 ~ onScroll ~ event:", event)
            const { scrollTop, scrollHeight, clientHeight } = event.target;
            if (scrollTop + clientHeight >= scrollHeight && !this.isFinished) {
                this.dataQuery();
            }
        },
        onLoad() {
            // 异步更新数据
            // setTimeout 仅做示例，真实场景中一般为 ajax 请求
            setTimeout(() => {
                for (let i = 0; i < 20; i++) {
                this.list.push(this.list.length + 1);
                }

                // 加载状态结束
                this.loading = false;

                // 数据全部加载完成
                if (this.list.length >= 80) {
                this.finished = true;
                }
            }, 1000);
            },
        showTime1(date) {
            if (date) {
                return formatter.formatDate(date, 'yyyy-MM-dd')
            } else {
                return '--'
            }
        },
        checkTime(date) {
            let currentDate = formatter.formatDate(new Date(), 'yyyy-MM-dd')
            let currentDateNum = Date.parse(currentDate)
            let dateNum = Date.parse(date)
            if (Number(currentDateNum) > Number(dateNum)) {
                return true
            } else {
                return false
            }
        },
        searchQuery() {
            // 设置start为0，数组清空，然后才加载数据
            this.start = 0
            this.query.data = []
            this.loadData()
        },
        reset() {
            this.identification = ''
            this.start = 0
            this.query.data = []
            this.loadData()
        },
        dataQuery() {
            console.log(this.recordsTotal,11111111111111111111111111,this.query.data);
            // if (this.loadFlag) {
            //     if (
            //         this.recordsTotal &&
            //         this.query.data.length >= this.recordsTotal
            //     ) {
            //         this.finished = true
            //     } else {
            //         this.loadFlag = false
            //         this.loadData()
            //     }
            // }
            if (
                    this.recordsTotal &&
                    this.query.data.length >= this.recordsTotal
                ) {
                    this.finished = true
                } else {
                    this.loadFlag = false
                    this.loadData()
                }
        },
        loadData(rqurl = this.url) {
            let self = this
            if (rqurl) {
                let params = { start: self.start, length: self.length }
                params[`query[craneType]`] = self.craneType
                params[`query[normalStatus]`] = 1
                if (self.otherSearch) {
                    params[`query[otherSearch]`] = self.otherSearch
                }
                self.$f7.preloader.show()
                self.$f7.request.postJSON(
                    rqurl,
                    params,
                    (r) => {
                        self.$f7.preloader.hide()
                        self.loading = false
                        if (r) {
                            if (_.isArray(r.data)) {
                                _.each(r.data, (item) => {
                                    self.query.data.push(item)
                                })
                                self.start += self.length
                                self.recordsTotal = r.recordsTotal
                                self.$emit('onAfterQuery', self.query.data)
                            }
                        }
                        self.loadFlag = true
                    },
                    (r) => {
                        self.loadFlag = true
                    }
                )
            }
        },
        // 关闭组件
        fnColse() {
            this.visible = false
        },
        // 提交
        async fnSave() {
            this.autoClose && this.fnColse()
            let newArr=JSON.parse(JSON.stringify(this.result))

          let isOk = true;
          let warnObj=newArr.find(pitem=> (pitem.enabledWork===false || pitem.enabledWork ===0));
          if(warnObj){
            isOk = false;
            this.$f7.dialog.alert(warnObj.personName + "该人员在一年内存在违章作业情况，暂时不允许再作业。！");
            return false;
          }

            // 筛选出跟上次的数据不一样的数据
            if(this.lastChooseList.length>0){
                newArr=newArr.filter(item=>!this.lastChooseList.includes(item))
            }
            let chooseArr=[]
            newArr.forEach(item=>{
                this.nowChooselist.forEach(citem=>{
                    if(citem.sectionId==item){
                        chooseArr.push(citem)
                    }
                })
            })
            this.$emit('save', chooseArr)
        },
        toggle(item, index) {
            this.$refs.checkboxes[index].toggle()
        },
    },
    watch: {
      result(newArr,oldArr){
        if(newArr.length==0){
            this.nowChooselist=[]
            return 
        }
        let thisArr=JSON.parse(JSON.stringify(newArr))
        // 筛选出跟上次的数据不一样的数据
        if(oldArr.length>0){
            newArr=newArr.filter(item=>!oldArr.includes(item))
        }
        if(newArr.length>0){
            newArr.forEach(item=>{
                this.query.data.forEach(citem=>{
                    if(citem.sectionId==item){
                        this.nowChooselist.push(citem)
                    }
                })
            })
        }else{
            this.nowChooselist=this.nowChooselist.filter(item=>thisArr.includes(item.sectionId))
        }
      }  
    },
}
</script>
<style lang="less" scoped>
@import url('../../../../assets/css/commonSelect.less');
.qzjx_label{
    color: #909DB6;
    flex-shrink: 0;
}
.qzjx_value{
  color: #61677A;
}
.search-list-item{
    flex-direction: column;
    h3{
        color: #242424;
        font-weight: 400;
        font-size: 16px;
        .tag{
            margin-left: 8px;
        }
    }
    p{
        display: flex;
        margin-top: 10px;
        font-size: 13px;
    }
}
</style>
